package org.gongliang.jfinal.controller;

import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.gongliang.jfinal.common.KConstant;
import org.gongliang.jfinal.common.base.ModelExt;
import org.gongliang.jfinal.common.base.Result;
import org.gongliang.jfinal.common.exception.BussinessException;
import org.gongliang.jfinal.common.exception.ExceptionEnum;
import org.gongliang.jfinal.model.User;

import com.google.common.collect.Maps;
import com.jfinal.core.Controller;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.TableMapping;
import com.jfinal.render.JsonRender;

public abstract class BaseController<M extends ModelExt<M>> extends Controller {

	private Class<M> clazz;
	protected String tablename=null;
	private final Integer PAGE_SIZE=10;         //默认每页显示10条数据
	private final Integer PAGE_INDEX=1;         //默认当前页为第一页
	
	protected List<Object> params=new ArrayList<Object>();
	
	@SuppressWarnings("unchecked")
	public BaseController() {
		ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
		this.clazz = (Class<M>) pt.getActualTypeArguments()[0];
		this.tablename=TableMapping.me().getTable(clazz).getName();
	}


	/**
	 * 通用查找全部
	 */
	public void findAll() {
		Result result = Result.success(ExceptionEnum.QUERY_SUCCESS);
		String sql = getSql();
		List<M> list = params == null || params.size() == 0 ? getBean(clazz, "").find(sql)
				: getBean(clazz, "").find(sql, params.toArray());
		result.setResData(list);
		render(new JsonRender(result).forIE());
	}

	/**
	 * 通用分页查找
	 */
	public void findAllByPage() {
		Result result = Result.success(ExceptionEnum.QUERY_SUCCESS);
		String sql = getSql();
		Page<M> list = params == null || params.size() == 0
				? getModel(clazz).paginateMysql(toPageIndex(), toPageSize(), sql)
				: getModel(clazz).paginateMysql(toPageIndex(), toPageSize(), sql, params.toArray());
		result.setResData(list.getList(), list.getTotalPage());
		render(new JsonRender(result).forIE());
	}


	/**
	 * 通用根据id查找
	 */
	public void findById(){
		Result result = Result.success(ExceptionEnum.QUERY_SUCCESS);
		M record = getBean(clazz, "").findById(getParaToInt("id"));
		if (record == null) {
			result.setExceptionEnum(ExceptionEnum.QUERY_ERROR);
		} else {
			result.setResExtraObj(record);
		}
		render(new JsonRender(result).forIE());
	}

	/**
	 * 通用新增
	 */
	public void saveORupdate(){
		Result result = Result.success();
		M m = getBean(clazz, "");
		boolean flag=false;
		if(m instanceof User&&StrKit.notBlank(m.getStr("password"))){
			m.set("password", HashKit.md5(HashKit.sha1(m.getStr("username")+m.getStr("password"))));
		}
		if(m instanceof User&&StrKit.isBlank(m.getStr("password"))){
			m.set("password", HashKit.md5(HashKit.sha1(m.getStr("username")+"123456")));
		}
		if(null!=m.get(TableMapping.me().getTable(clazz).getPrimaryKey()[0])){
			flag=m.update();
		}else{
			flag=m.save();
		}
		if(flag){
			result.setExceptionEnum(ExceptionEnum.INSERT_SUCCESS);
			render(new JsonRender(result).forIE());
		}else{
			result.setExceptionEnum(ExceptionEnum.INSERT_ERROR);
			render(new JsonRender(result).forIE());
		}
	}

	/**
	 * 通用删除
	 */
	public void deleteById() {
		Result result = Result.success(ExceptionEnum.DELETE_SUCCESS);
		if (!getBean(clazz, "").delete()) {
			result.setExceptionEnum(ExceptionEnum.DELETE_ERROR);
		}
		render(new JsonRender(result).forIE());
	}
	/**
	 * 批量id删除
	 */
	public void deleteByIds() {
		Integer[] ids=getParaValuesToInt("ids[]");
		Result result = Result.success("批量删除成功!");
		if (ids == null || ids.length <= 0) {
			throw new BussinessException(ExceptionEnum.IDS_NOT_NULL);
		}
		for(int id: ids)
			getBean(clazz, "").deleteById(id);
		render(new JsonRender(result).forIE());
	}

	/**
	 * 获取当前页
	 * @return 当前页码
	 */
	protected int toPageIndex(){
		String pageIndex=getPara("page")==null?getPara("pageIndex"):getPara("page");
		if(StrKit.isBlank(pageIndex)){
			return PAGE_INDEX;
		}
		return Integer.parseInt(pageIndex);
	}
	/**
	 * 获取每页显示多少条数据
	 * @return 当前页码
	 */
	protected int toPageSize(){
		String pageSize=getPara("rows")==null?getPara("pageSize"):getPara("rows");
		if(StrKit.isBlank(pageSize)){
			return PAGE_SIZE;
		}
		return Integer.parseInt(pageSize);
	}
	
	@Override
	public String getPara(String name) {
		if(StrKit.notBlank(getRequest().getParameter(name))){
			return getRequest().getParameter(name);
		}
		return null;
	}
	protected User getUser(){
		return getSessionAttr(KConstant.USER_SESSION);
	}

	public Map<String,String> getparamaterMap(){
		Map<String,String> params=Maps.newHashMap();
		Map<String,String[]> param=getParaMap();
		for(String key: param.keySet()){
			params.put(key, getPara(key));
		}
		return params;
	}

	/**
	 * 获取动态sql
	 */
	protected abstract String getSql();
}
